//
//  HomeTableViewController.m
//  coca
//
//  Created by 张帅 on 15/9/26.
//  Copyright © 2015年 ZhangShuai. All rights reserved.
//

#import "HomeTableViewController.h"
#import "UserAccountViewModel.h"

#import "NetworkTools.h"
#import <ReactiveCocoa/ReactiveCocoa.h>
#import <SVProgressHUD/SVProgressHUD.h>
#import "Status.h"
#import "StatusListViewModel.h"

#import "StatusForwardCell.h"
#import "StatusNormalCell.h"
#import "HMRefreshControl.h"
#import "UILabel+Contenlable.h"
#import "PhotoBrowserViewController.h"
#import "PhotoBrowserAnimator.h"
#import "SQliteManager.h"
@interface HomeTableViewController ()

@property(nonatomic,strong) StatusListViewModel *statusListViewModel;

@property(nonatomic,strong) UIActivityIndicatorView *pullupView;

@property(nonatomic,assign) BOOL isFirstLoadData;


@property(nonatomic,strong) UILabel *pulldownTipLabel;

@property(nonatomic,strong)PhotoBrowserAnimator *photoBrowserAnimator;
@end

@implementation HomeTableViewController


-(StatusListViewModel *)statusListViewModel{
    if (_statusListViewModel==nil) {
        _statusListViewModel=[[StatusListViewModel alloc] init];
    }
    return _statusListViewModel;
}


-(UIActivityIndicatorView *)pullupView{
    if (_pullupView==nil) {
        
          _pullupView =[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:(UIActivityIndicatorViewStyleWhite)];
        _pullupView.color =[UIColor darkGrayColor];
        
    }

    return _pullupView;
}


-(UILabel *)pulldownTipLabel{
    if (_pulldownTipLabel==nil) {
        _pulldownTipLabel =[[UILabel alloc] initWithTitle:nil color:[UIColor orangeColor] sizeFont:14];
        
        [_pulldownTipLabel setBackgroundColor:[UIColor greenColor]];
//        _pulldownTipLabel.textAlignment =NSTextAlignmentCenter;
        [_pulldownTipLabel setTextAlignment:NSTextAlignmentCenter];
        [self.navigationController.navigationBar insertSubview:_pulldownTipLabel atIndex:0];
    }
    return _pulldownTipLabel;
}

-(PhotoBrowserAnimator *)photoBrowserAnimator{
    if (_photoBrowserAnimator==nil) {
        _photoBrowserAnimator=[[PhotoBrowserAnimator alloc] init];
    }
    return _photoBrowserAnimator;
}
- (void)viewDidLoad {
    [super viewDidLoad];

    if (![UserAccountViewModel sharedUserAccount].userLogon) {
        
        [self.visitorView setupInfoImageName:nil message:@"关注一些人，回这里看看有什么惊喜"];
        return;
    }
    
    [SQliteManager shareInstance] ;

    /**
     *  通知
     */
    
    [[NSNotificationCenter defaultCenter] addObserverForName:HMStatusPictureViewSelectedPhotoNotification object:nil queue:nil usingBlock:^(NSNotification * _Nonnull note) {
    
        NSDictionary *dict  =note.userInfo;
        
        NSMutableArray *urls  =dict[HMStatusPictureViewSelectedPhotoURLsKey];
        
        if (!urls) {
            return ;
        }
        
        NSIndexPath *indexPath =dict[HMStatusPictureViewSelectedPhotoIndexPathKey];
        if (!indexPath) {
            return;
        }
        
        StatusPictureView *picView = note.object;
     
        if (!picView) {
            return;
        }
        
        
        PhotoBrowserViewController *vc = [[PhotoBrowserViewController alloc] initWithURL:urls indexPath:indexPath];
        
        // 以下两句代码能够保证 Modal 之后，源视图控制器不会从屏幕上移除
        // 1. 指定动画的提供者 transitioning - 转场，从一个界面跳转到另外一个界面的动画效果

        vc.transitioningDelegate=self.photoBrowserAnimator;
        // 2. 指定 modal 展现样式是自定义的

        vc.modalPresentationStyle = UIModalPresentationCustom;
        
          CGRect fromRect =[picView screenRect:indexPath];
        
          CGRect toRect=[picView fullScreenRect:indexPath];
        
     
        [self.photoBrowserAnimator  prepareAnimatorPicView:picView fromRect:fromRect toRect:toRect url:urls[indexPath.item]];
        
        
         [self.navigationController presentViewController:vc animated:YES completion:nil];
        
        
    }];
    
    
    
    self.isFirstLoadData =YES;
    [self prepareTableView];
    [self loadData];
    
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
}


-(void)prepareTableView{

    [self.tableView registerClass:[StatusForwardCell class] forCellReuseIdentifier:HMStatusForwardCellID];
    
    
    [self.tableView registerClass:[ StatusNormalCell class] forCellReuseIdentifier:HMStatusNormalCellID];
    
    
    self.tableView.estimatedRowHeight = 300;
    
    self.tableView.separatorStyle  = UITableViewCellSeparatorStyleNone;
    
    
    self.refreshControl =[HMRefreshControl new];
    
    [self.refreshControl addTarget:self action:@selector(loadData) forControlEvents:(UIControlEventValueChanged)];
  
    self.tableView.tableFooterView = self.pullupView;
   
}

-(void)loadData{
    
    
    // beginRefreshing只会播放刷新动画，不会加载数据

    [self.refreshControl beginRefreshing];

    [[self.statusListViewModel loadStatusesWithPullupRefresh:self.pullupView.isAnimating] subscribeNext:^(  NSNumber *result) {
      
        NSInteger  count = result.integerValue;
        if (!self.isFirstLoadData) {
            NSLog(@"刷新到%ld微博",count);
            [self showPulldownTipsWithCount:count];
        }
        
    } error:^(NSError *error) {
        [self endLoadData];
         NSLog(@"%@",error);
    } completed:^{
//        [self.refreshControl endRefreshing];

        [self endLoadData];
        [self.tableView reloadData];
        self.isFirstLoadData=NO;

    }];

}


-(void)showPulldownTipsWithCount:(NSInteger)count{


    NSString  *title = count==0 ? @"没有刷到微博":[NSString stringWithFormat:@"刷到%ld条微博",count];
    
 
    CGFloat h = 44;
    CGRect rect = CGRectMake(0, -2*h, [UIScreen mainScreen].bounds.size.width, h);
    
    self.pulldownTipLabel.text =title;
    self.pulldownTipLabel.frame = rect;
    
    [UIView animateWithDuration:1 animations:^{
        self.pulldownTipLabel.frame =CGRectOffset(rect,0, 3*h);
    }completion:^(BOOL finished) {
      
        [UIView animateWithDuration:1 animations:^{
            self.pulldownTipLabel.frame =  rect;
        }];
    }];

}
-(void)endLoadData{
    // 关闭刷新控件
    [self.refreshControl endRefreshing];
     // 关闭上拉刷新动画
    [self.pullupView  stopAnimating];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    return  self.statusListViewModel.statuses.count;
}


-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{


    StatusViewModel *statusViewModel = [self.statusListViewModel statuses][indexPath.row];
    
    
    StatusCell *cell =[tableView dequeueReusableCellWithIdentifier:[statusViewModel cellID] forIndexPath:indexPath];
    
    // 1. 获取微博数据
    cell.statusViewModel=statusViewModel;
    
    // 4. 判断当前的 indexPath 是否是数组的最后一项，如果是，开始上拉动画

    if ((indexPath.row == self.statusListViewModel.statuses.count-1 )&&! self.pullupView.isAnimating) {
        
        NSLog(@"显示上拉视图");
        [self.pullupView startAnimating];
        [self loadData];
    }
    
    
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    StatusViewModel *viewModel = self.statusListViewModel.statuses[indexPath.row];
    
    if (viewModel.rowHeight>0) {
        NSLog(@"返回缓存行高");
        return viewModel.rowHeight;
    }
    StatusCell *cell =[tableView dequeueReusableCellWithIdentifier:[viewModel cellID]];
            // 3. 记录行高
    viewModel.rowHeight = [cell rowHeight:viewModel];
    return  viewModel.rowHeight;
}


@end










